package org.mspring.mlog.api.duoshuo.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.hibernate.criterion.Restrictions;
import org.mspring.mlog.api.duoshuo.DSConst;
import org.mspring.mlog.api.duoshuo.DSURLConst;
import org.mspring.mlog.api.duoshuo.entity.DSComment;
import org.mspring.mlog.api.duoshuo.entity.Sync2DS;
import org.mspring.mlog.api.duoshuo.service.DuoshuoService;
import org.mspring.mlog.entity.Comment;
import org.mspring.platform.persistence.hibernate.BaseHibernateDao;
import org.mspring.platform.persistence.hibernate.common.EnhancedRule;
import org.mspring.platform.utils.DateUtils;
import org.springframework.stereotype.Service;

/**
 * 
 * @author Gao Youbo
 * @since 2013年9月23日
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Service
public class DuoshuoServiceImpl extends BaseHibernateDao implements DuoshuoService {

    @Override
    public void sync2ds(int batch) throws ClientProtocolException, IOException {
        // TODO Auto-generated method stub
        int totalPage = getTotalPage(batch);
        if (totalPage > 0) {
            for (int i = 1; i <= totalPage; i++) {
                HttpClient httpClient = new DefaultHttpClient();
                Sync2DS sync2dsEntity = getSync2dsEntity(i, batch);
                List<NameValuePair> nvps = sync2dsEntity.getNameValuePairs();
                HttpPost httpPost = new HttpPost(DSURLConst.SYNC2DS);
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
                httpClient.execute(httpPost);
            }
        }
    }

    @Override
    public void sync2local() {
        // TODO Auto-generated method stub

    }

    /**
     * 分页获取同步数据
     * 
     * @param page
     * @param pagesize
     * @return
     */
    protected Sync2DS getSync2dsEntity(int page, int pagesize) {
        EnhancedRule rule = new EnhancedRule();
        rule.add(Restrictions.eq("status", Comment.Status.APPROVED));
        rule.setPageSize(pagesize);
        rule.setPage(page);
        List<Comment> comments = getHibernateTemplate().list(Comment.class, rule);

        Sync2DS entity = new Sync2DS();
        entity.setShort_name(DSConst.SHORT_NAME);
        entity.setSecret(DSConst.SECRET);
        List<DSComment> dsComments = new ArrayList<DSComment>();
        for (Comment comment : comments) {
            DSComment dsc = null;
            try {
                dsc = toDSComment(comment);
            } catch (Exception e) {
                // TODO: handle exception
                continue;
            }
            dsComments.add(dsc);
        }
        entity.setPosts(dsComments);
        return entity;
    }

    /**
     * 同步数据总页数
     * 
     * @param pagesize
     * @return
     */
    protected int getTotalPage(int pagesize) {
        EnhancedRule rule = new EnhancedRule();
        rule.add(Restrictions.eq("status", Comment.Status.APPROVED));
        int totalCount = getHibernateTemplate().count(Comment.class, rule);

        if (totalCount < 0) {
            return -1;
        }

        int count = totalCount / pagesize;
        if (totalCount % pagesize > 0) {
            count += 1;
        }
        return count;
    }

    /**
     * 系统评论数据转换成多说数据对象
     * 
     * @param comment
     * @return
     */
    protected DSComment toDSComment(Comment comment) {
        DSComment dsc = new DSComment();
        dsc.setPost_key("CMT_" + comment.getId());
        dsc.setThread_key("POST_" + comment.getPost().getId());
        dsc.setMessage(comment.getContent());

        // dsc.setPost_id("CMT_" + comment.getId());
        if (comment.getParent() != null && comment.getParent().getId() != null) {
            dsc.setParent_key(comment.getParent().getId().toString());
        }
        dsc.setAuthor_key("");
        dsc.setAuthor_name(comment.getAuthor());
        dsc.setAuthor_email(comment.getUrl());
        dsc.setIp(comment.getPostIp());
        dsc.setAgent(comment.getAgent());
        dsc.setLikes("");
        dsc.setReports("");
        dsc.setCreated_at(DateUtils.format(comment.getCreateTime(), DateUtils.YYYY_MM_DD_HH_MM_SS));
        if (Comment.Status.APPROVED.equals(comment.getStatus())) {
            dsc.setStatus(DSComment.Status.APPROVED);
        } else if (Comment.Status.WAIT_FOR_APPROVE.equals(comment.getStatus())) {
            dsc.setStatus(DSComment.Status.PENDING);
        } else {
            dsc.setStatus(DSComment.Status.DELETED);
        }
        return dsc;
    }

}
